<?php

namespace app\api\middleware;

use app\api\extend\firebase\Jwt;
use think\facade\Config;

class CheckAuth
{
    public function handle($request, \Closure $next)
    {
        $controller = $request->controller(true);
        //方法
        $action = $request->action(true);

        // 不需要登录处理
        $noNeedLoginConfig = Config::get('no_need_login');
        if (isset($noNeedLoginConfig[$controller])) {
            if ($noNeedLoginConfig[$controller] === '*' || in_array($action,$noNeedLoginConfig[$controller])) {
                return $next($request);
            }
        }


        $token = $request->header('access-token');
        if ($token === null) {
            return show(httpCode:401);
        }
        $jwt = new Jwt();
        $userInfo = $jwt->decrypt($token);
        if ($userInfo === false) {
            return show(httpCode:401);
        }

        $request->userInfo = [
            'userId' => $userInfo['data']->userId
        ];


        return $next($request);
    }

}